package project.vip.utils;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;



/**

 * @author wuhengbo@joeone.net 2016-01-27

 * WxUtils工具类：SHA1加密，随机字符串

 */

public class VipWxUtils {

	

	

	public static String FormatBizQueryParaMap(HashMap<String, String> paraMap,

			boolean urlencode) throws Exception {



		String buff = "";

		try {

			List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(

					paraMap.entrySet());



			Collections.sort(infoIds,

					new Comparator<Map.Entry<String, String>>() {

						public int compare(Map.Entry<String, String> o1,

								Map.Entry<String, String> o2) {

							return (o1.getKey()).toString().compareTo(

									o2.getKey());

						}

					});



			for (int i = 0; i < infoIds.size(); i++) {

				Map.Entry<String, String> item = infoIds.get(i);

				//System.out.println(item.getKey());

				if (item.getKey() != "") {

					

					String key = item.getKey();

					String val = item.getValue();

					if (urlencode) {

						val = URLEncoder.encode(val, "utf-8");// utf-8



					}

//					buff += key.toLowerCase() + "=" + val + "&";

					buff += key + "=" + val + "&";



				}

			}



			if (!buff.equals("")){

				buff = buff.substring(0, buff.length() - 1);

			}

		} catch (Exception e) {

			throw new Exception(e.getMessage());

		}

		return buff;

	}



	public final static String Sha1(String s) {

		 System.out.println("加密前的签名："+s);



        char hexDigits[]={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };       

        try {

            byte[] btInput = s.getBytes();

            MessageDigest mdInst = MessageDigest.getInstance("sha-1");

            mdInst.update(btInput);

            byte[] md = mdInst.digest();

            int j = md.length;

            char str[] = new char[j * 2];

            int k = 0;

            for (int i = 0; i < j; i++) {

                byte byte0 = md[i];

                str[k++] = hexDigits[byte0 >>> 4 & 0xf];

                str[k++] = hexDigits[byte0 & 0xf];

            }

            String rtn = new String(str);

   		 	System.out.println("加密后的签名："+rtn);

            return rtn;

        } catch (Exception e) {

            e.printStackTrace();

            return null;

       }

	}

	/**

	 * 随机字符串

	 * @return

	 */

	public static String CreateNoncestr() {

		String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

		String res = "";

		for (int i = 0; i < 16; i++) {

			Random rd = new Random();

			res += chars.charAt(rd.nextInt(chars.length() - 1));

		}

		return res;

	}

	


}